package com.rykj.energy.task.message.construct;

import com.rykj.energy.common.utils.CollectionUtils;
import com.rykj.energy.database.pojo.BasicCamera;
import com.rykj.energy.database.service.ICameraService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 *定时更新摄像头状态
 */
@Component
@Slf4j
public class CameraQuartz {

    @Autowired
    private ICameraService cameraService;

    //是否开启更新摄像头在线状态
    @Value("${camera.update.lineStatus:false}")
    private String cameraUpdateLineState;

    //加检查更新摄像头状态线程数量
    @Value("${check.camera.threadNum:5}")
    private Integer cameraTheadNum;

    //@Scheduled(cron = "0 0 0/8 * * ?")
    //每隔一小时更新摄像头在线状态
    public void updateCameraLineStatus(){
        try {
            log.info("=====开始更新摄像头状态====start==="+cameraUpdateLineState);
            if("true".equals(cameraUpdateLineState)){
                List<BasicCamera> cameras = cameraService.getAllCameras();
                if(CollectionUtils.isNotEmpty(cameras)){
                    ExecutorService executor = Executors.newFixedThreadPool(cameraTheadNum);
                    try {
                        for (BasicCamera camera : cameras) {
                            executor.submit(new CameraLineStatus(camera,cameraTheadNum));
                        }
                    }finally {
                        executor.shutdown();
                    }
                }
            }
            log.info("=====结束更新摄像头状态====end===");
        }catch (Exception e){
           log.error("===更新摄像头状态异常===",e);
        }
    }

    public class CameraLineStatus implements Callable<Integer>{
        private BasicCamera camera;
        private Integer n;
        public CameraLineStatus(BasicCamera camera,Integer n){
            this.camera=camera;
            this.n=n;
        }

        @Override
        public Integer call() throws Exception {
            cameraService.updateCameraLineStatus(camera);
            return n;
        }

    }
}
